const { todoService } = require('../../services/index');
const app = getApp();

Page({
  data: {
    activeTab: 0,
    todoList: [],
    isLoading: false,
    userInfo: null
  },

  onLoad() {
    // 检查登录和情侣状态
    if (!app.routeInterceptor()) return;
    
    this.setData({
      userInfo: app.globalData.userInfo
    });
    
    // 加载待办数据
    this.loadTodoData();
  },

  onShow() {
    // 每次显示页面时检查数据更新
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
    }
    this.loadTodoData();
  },

  onTabChange(e) {
    this.setData({
      activeTab: e.detail.index
    });
    this.loadTodoData();
  },

  async loadTodoData() {
    if (!app.globalData.coupleInfo) return;
    
    this.setData({ isLoading: true });
    
    try {
      // 获取待办列表
      const todoList = await todoService.getCoupleTodos(
        app.globalData.coupleInfo.id,
        { status: this.data.activeTab === 0 ? null : this.data.activeTab - 1 }
      );
      
      // 格式化日期并添加assigneeName
      const formattedList = todoList.map(item => ({
        ...item,
        dueDate: this.formatDate(item.dueDate),
        assigneeName: item.assigneeId === app.globalData.userInfo.id ? 
          '我' : 
          app.globalData.coupleInfo.partnerName || 'TA'
      }));
      
      this.setData({
        todoList: formattedList
      });
      
    } catch (error) {
      console.error('加载待办失败:', error);
    } finally {
      this.setData({ isLoading: false });
    }
  },

  async onStatusChange(e) {
    const { value } = e.detail;
    const { id } = e.currentTarget.dataset;
    const status = value ? 1 : 0;
    
    try {
      await todoService.updateTodoStatus(id, status);
      this.loadTodoData();
    } catch (error) {
      console.error('更新状态失败:', error);
    }
  },

  formatDate(dateStr) {
    if (!dateStr) return '无期限';
    const date = new Date(dateStr);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  },

  navToAddTodo() {
    wx.navigateTo({
      url: '/pages/todo/add'
    });
  }
});